package com.itcast.demo.validate.controller;

import com.itcast.demo.validate.exception.CustomException;
import com.itcast.demo.validate.pojo.User;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotNull;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/validate")
public class ValidateController1 {

    // 实体类参数校验
    @PostMapping("/test2")
    public void test2(@RequestBody @Valid User user, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            System.out.println(bindingResult.getFieldError().getDefaultMessage());
            // 返回第一条错误信息
            System.out.println(bindingResult.getAllErrors().get(0).getDefaultMessage());
            throw new CustomException(bindingResult.getFieldError().getDefaultMessage(),
                    HttpStatus.BAD_REQUEST.value()+"", bindingResult.getFieldError().getObjectName());
        }
        System.out.println("test2");
    }

    // 自定义注解校验
    @PostMapping("/test3")
    public void test3(@RequestBody @Validated User user) {
        System.out.println("test3");
    }

}
